package parsers.lectureRoom;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import parsers.CommonMethods;

import model.Building;
import model.LectureRoom;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

public class LectureRoomsParser
{
	private Building building;
	
	public LectureRoomsParser(Building building)
	{
		this.building = building;
	}
	
	public Building parse(boolean linkWithParent) throws IOException
	{
		Building building = null;
		
		if(linkWithParent)
		{
			building = this.building;
		}
		else
		{
			building = new Building(this.building.getName(), this.building.getDescription(), this.building.getAddress());
			building.setId(this.building.getId());
			building.setLink(CommonMethods.parseLink(this.building.getLink()));
		}
		
		Source source = new Source(new URL(this.building.getLink()));
		List<Element> elements = source.getAllElements(HTMLElementName.TR);
		
		for (Element element : elements)
		{
			String name = element.toString();
			
			if(name.contains("bgcolor"))
			{
				
				List<Element> subElements = element.getAllElements(HTMLElementName.TD);
				
				String link = subElements.get(0).getContent().getFirstElement().getAttributeValue("href");
				String lectureRoomName = subElements.get(0).getContent().getFirstElement().getContent().toString();
				String capacity = CommonMethods.checkSpace( subElements.get(1).getContent().toString() );
				String type = subElements.get(2).getContent().toString();
				String unit = subElements.get(3).getContent().toString();
				
				LectureRoom lr = building.createLectureRoom(lectureRoomName, capacity, type, unit);
				lr.setLink(CommonMethods.parseLink(link));
			}
		}
		
		return building;
	}
	
	/*public static void main(String[] args) throws MalformedURLException, IOException
	{
		Building b = new Building("", "", "");
		b.setLink("file:/D:/test8.html");
		LectureRoomsParser lrp = new LectureRoomsParser(b);
		Building building = lrp.parse(false);
		System.out.println(building);
	}*/
}
